<?php

require_once 'authpage.php';

/**
 * Description of MessageController
 *
 * @author user
 */
class MessageController extends AuthpageController {

    private $msgperpage = 6;
    private $msgpage;

    public function index($page = null) {
        if (isset($_POST['key'])) {
            $key = $_POST['key'];
            //If user is sending msg ...
            if ($key == 'send msg')
                $this->sendMsgHandling();
            else if ($key == 'reply')
                $this->replyMsgHandling();
        }

        //validate page
        $page = $page == null ? 0 : $page;
        $startIdx = $page * $this->msgperpage;
        
        $msgpage = $page;

        //Cari semua topik msg yang diikuti user :
        //Cari semua msg yang ada di msg_master_id yang ditujukan kepada si user
        //(liat dari msg_user) yang parent_msg_id nya null
        $all_messages = array();
        $query = "
            SELECT msg_master.*
            FROM `msg_master`
            LEFT JOIN  `msg_user` ON ( msg_master.id = msg_user.msg_master_id )
            WHERE  `receiver_id` =" . $this->auth_user->user->id . "
            GROUP BY msg_master.parent_msg_id
            ORDER BY msg_master.id DESC
            LIMIT $startIdx, " . ($this->msgperpage + 1);
        $msg_master = new ORM('msg_master');
        $msg_topics = $msg_master->query($query);
        $nextpageavail = count($msg_topics) > $this->msgperpage ? $page + 1 : null;
        if (count($msg_topics) > $this->msgperpage) {
            array_pop($msg_topics);
        }

        //traverse each topic and find all posts that correspond to that topic
        foreach ($msg_topics as $i => $topic) {
            //Get master post
            $master_post = new ORM('msg_master');
            $master_post->where("`id` = $topic->parent_msg_id")->find();

            //Get posts for this topic that is targeted to user
            $query = "
                SELECT msg_master.*
                FROM `msg_master`
                LEFT JOIN  `msg_user` ON ( msg_master.id = msg_user.msg_master_id )
                WHERE  `receiver_id` =" . $this->auth_user->user->id . " AND `parent_msg_id` = $master_post->id
            ";
            $posts = $master_post->query($query);
            $all_messages[$master_post->id] = $posts;
        }

        //Set the Inbox view
        $this->view->content = View::factory('message/index');
        $this->view->content->messages = $all_messages;
        $this->view->content->user = $this->auth_user->user;
        $this->view->content->nextpage = $nextpageavail;
        $this->view->content->prevpage = $page > 0 ? $page - 1 : null;


        //AJAX VIEW
        if (isset($_POST["ajax"])) {
            $this->view = View::factory("ajax", array("content" => $this->view->content));
            return;
        }
    }

    public function del($msgMasterId) {
        $msg_user = new ORM('msg_user');
        $userid = $this->auth_user->user->id;
        $msg_user->where("`msg_master_id` = $msgMasterId AND `receiver_id` = $userid")->find();
        $msg_user->delete();

        URL::redirect("message");
    }

    private function sendMsgHandling() {
        //Validating
        if (($_POST['to']) === "") {
            $this->view->error = "Unable to send message: no recipient defined";
            return;
        }
        if (($_POST['content']) === "") {
            $this->view->error = "Unable to send message: empty message body";
            return;
        }

        //
        $isNewMsg = !isset($_POST['parent_msg_id']);
        if ($isNewMsg) {
            $_POST['to'] .= " " . $this->auth_user->user->username;
            $_POST['parent_msg_id'] = '';
        }

        //Validate target user
        $recipientnames = explode(" ", $_POST['to']);
        $recipientids = array();
        $invalidids = array();
        foreach ($recipientnames as $name) {
            //Get id for the name
            $userorm = new ORM('user');
            $userorm->where("`username` = '$name'")->find();
            if ($userorm->id == null)
                $invalidids[] = $name;
            else
                $recipientids[] = $userorm->id;
        }

        //Handle any invalid recipient
        if (count($invalidids) > 0) {
            $errmsg = "Message is not send to these recipients because of invalid username :";
            foreach ($invalidids as $invalid) {
                $errmsg .= " $invalid,";
            }
            rtrim($errmsg, ",");
            $this->view->error = $errmsg;
        }

        $recipientids = array_values(array_unique($recipientids));
        if (count($recipientids) <= 1) {
            $this->view->error = "Message couldn't be sent because there is no valid recipient";
            return;
        }

        //Get recipients
        $recipients = array();
        foreach ($recipientids as $id) {
            $user = new ORM('user');
            $user->find($id);
            $recipients[] = $user;
        }

        //Add it to master_msg db
        $orm = new ORM('msg_master');
        $orm->parent_msg_id = $_POST['parent_msg_id'];
        $orm->header = $_POST['title'] == null ? "- No Subject -" : $_POST['title'];
        $orm->from = $this->auth_user->user->id;
        $to = "";
        foreach ($recipients as $recipient)
            $to .= $recipient->username . " ";
        $orm->to = rtrim($to);
        $orm->message_text = $_POST['content'];
        $orm->save();

        //Our constraint, if this is a new topic, set it's parent as itself and sender as recipient too
        if ($isNewMsg) {
            $orm->parent_msg_id = $orm->id;
            $orm->save();
        }

        //Add it to msg_user list
        foreach ($recipients as $recipient) {
            $msgorm = new ORM('msg_user');
            $msgorm->receiver_id = $recipient->id;
            $msgorm->msg_master_id = $orm->id;
            $msgorm->save();
        }

        URL::redirect("message/index/" . $this->msgpage);
    }

    private function replyMsgHandling() {
        //Prepare vars
        $master_post = new ORM('msg_master');
        $parent_msg_id = $_POST['parent_msg_id'];
        $master_post->where("`id` = $parent_msg_id")->find();
        $_POST['to'] = $master_post->to;
        $_POST['title'] = "RE : " . $master_post->header;

        //Handled the same way as sending new msg
        $this->sendMsgHandling();
    }

}

?>
